# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '18042600001886': {  # dwc 快捷1.3%，0---5000，do结算。
        'API_KEY': 'DF09091698F5D66022B2434B212FAD92',
        'orgNo': '8180400279',
        'gateway': 'http://www.lszx0578.com:8086/mpcctp/cashier/pay.ac',
        'query_gateway': 'http://www.lszx0578.com:8086/mpcctp/cashier/query.ac',
    },
    '16121900001774': {  # test
        'API_KEY': 'FFFFFFFFFFFFFFFF',
        'orgNo': '8161000204',
        'gateway': 'http://47.98.155.45:8889/tran/cashier/pay.ac',
        'query_gateway': 'http://47.98.155.45:8889/tran/cashier/query.ac',
    },
    '18061500001903': {  # 商银信支付 loki 支付宝：3%（1---5000整数充值），t0结算，结算时间（9：00----17：00）两小时下发一次。
        'API_KEY': '891906DAFC3C41F370F214DEADE0F2C9',
        'orgNo': '8180600283',
        'gateway': 'http://47.98.155.45:8889/tran/cashier/pay.ac',
        'query_gateway': 'http://47.98.155.45:8889/tran/cashier/query.ac',
    },
    '18081400002011': {  # 商银信支付 loki 支付宝：3%（1---5000整数充值），t0结算，结算时间（9：00----17：00）两小时下发一次。
        'API_KEY': '0F031EFEE6B04F211851AF6EA3CEA8C8',
        'orgNo': '0180800407',
        'gateway': 'http://212.64.101.56:8889/tran/cashier/pay.ac',
        'query_gateway': 'http://212.64.101.56:8889/tran/cashier/query.ac',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_org_no(mch_id):
    return APP_CONF[mch_id]['orgNo']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("zhangxunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


# 交易类型:
# 0402:微信扫码
# 0405:微信H5
# 0701:QQ钱包（H5）
# 0702:QQ钱包扫码（直连）
# 0502:支付宝扫码
# 0505:支付宝H5(网页表单提交)
# 0901:京东扫码
# 0302: 快捷
# 0601:网关支付(直连银行)
# 0801:银联扫码(收银行)
def _get_pay_type(service):
    if service == 'alipay':
        return '0505'
    elif service == 'alipay1':
        return '0508'
    elif service == 'alipay2':
        return '0506'
    elif service == 'quick':
        return '0302'
    elif service == 'qq':
        return '0701'
    elif service == 'jd':
        return '0901'
    else:
        return '0405'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('version', '2.1'),
        ('orgNo', _get_org_no(app_id)),
        ('custId', app_id),
        ('custOrderNo', str(pay.id)),
        ('tranType', _get_pay_type(service)),
        ('payAmt', str(int(pay_amount * 100))),
        ('backUrl', '{}/pay/api/{}/zhangxunpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('frontUrl', '{}/pay/api/{}/zhangxunpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('goodsName', 'charge'),
    ))

    p_dict['sign'] = generate_sign(p_dict, api_key)
    _LOGGER.info('zhangxunpay before data: %s', p_dict)
    if service in ['alipay', ]:
        html_text = _build_form(p_dict, _get_gateway(app_id))
        cache_id = redis_cache.save_html(pay.id, html_text)
    else:
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_gateway(app_id), data=p_dict, headers=headers, timeout=3)
        _LOGGER.info('zhangxunpay rsp data: %s', response.text)
        cache_id = redis_cache.save_html(pay.id, json.loads(response.text)['busContent'])
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SC000000
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("zhangxunpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['custOrderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zhangxunpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['ordStatus'])
    trade_no = data['prdOrdNo']
    total_fee = float(data['ordAmt']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 订单操作成功时返回.
    # 00:未交易
    # 01:成功
    # 02:失败
    # 06:未支付.
    if trade_status == '01':
        _LOGGER.info('zhangxunpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('version', '2.1'),
        ('orgNo', _get_org_no(app_id)),
        ('custId', app_id),
        ('custOrderNo', pay_order.id),
    ))
    p_dict['sign'] = generate_sign(p_dict, api_key)
    _LOGGER.info('zhangxunpay query data, %s', p_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info('zhangxunpay query rsp: %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['ordStatus'])
        total_fee = float(data['payAmt']) / 100.0
        trade_no = data['prdOrdNo']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == '01' and total_fee > 0:
            _LOGGER.info('zhangxunpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
